<?php
/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/8/1
 * Time: 上午7:37
 */

namespace App\Services;


use App\Models\Notice;

class NoticeService extends Service
{

    public static function getNoticeList($limit, $offset, $order = 'desc')
    {
        $query = Notice::where('status', 1);
        $total = $query->count();
        $notices = $query->orderBy('id', $order)->limit($limit)->offset($offset)->get();
        $data = [];
        foreach ($notices as $notice) {
            $data[] = [
                'id' => $notice->id,
                'type' => $notice->type,
                'title' => $notice->title,
                'created_at' => local_date($notice->created_at, 'Y-m-d H:i:s')
            ];
        }

        return [
            'total' => $total,
            'rows' => $data,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function getNoticeDetail($id)
    {
        $notice = Notice::where('id', $id)->first();

        if (!$notice) {
            return [];
        }
        return [
            'data' => [
                'id' => $notice->id,
                'type' => $notice->type,
                'title' => $notice->title,
                'content' => $notice->content,
                'created_at' => local_date($notice->created_at, 'Y-m-d H:i:s')
            ]
        ];
    }

    public static function saveNotice($data)
    {
        $notice = new Notice();
        if (array_key_exists('id', $data) && $data['id']) {
            $notice = Notice::where('id', $data['id'])->first();
        } else {
            $notice->created_at = date('Y-m-d H:i:s', time());
        }
        foreach ($data as $key => $value) {
            $notice->$key = $value;
        }
        $notice->updated_at = date('Y-m-d H:i:s', time());
        $notice->save();
    }

    public static function deleteNotice($id)
    {
        $notice = Notice::where('id', $id)->first();
        $notice->status = 0;
        $notice->updated_at = date('Y-m-d H:i:s', time());
        $notice->save();
    }
}